<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--部门数据-->
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input
            v-model="deptName"
            placeholder="请输入部门名称"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
            :data="deptOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            default-expand-all
            @node-click="handleNodeClick"
          />
        </div>
      </el-col>
      <!--用户加分项信息-->
      <el-col :span="20" :xs="24">
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="auto">

          <el-form-item label="荣誉" prop="plusGradeItemGloryId">
            <el-cascader :options="options"
                         ref="myCascader2"
                         v-model="queryParams.plusGradeItemGloryId"
                         @change="cascaderChange2"
                         :props="{ expandTrigger: 'hover' }"
                         :show-all-levels="false"
                         :key="isResouceShow"
                         size="small"
            >

            </el-cascader>
          </el-form-item>
          <el-form-item label="获得时间" prop="plusGradeItemTime">
            <el-date-picker clearable size="small"
                            v-model="queryParams.plusGradeItemTime"
                            type="date"
                            value-format="yyyy-MM-dd"
                            placeholder="选择加分项获得时间"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="学院状态" prop="statusCollege">
            <el-select v-model="queryParams.statusCollege" placeholder="请选择学院状态" clearable size="small">
              <el-option
                v-for="dict in statusCollegeOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="学生处状态" prop="statusOffice">
            <el-select v-model="queryParams.statusOffice" placeholder="请选择学生处状态" clearable size="small">
              <el-option
                v-for="dict in statusOfficeOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['student:item:add']"
            >新增
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="el-icon-edit"
              size="mini"
              :disabled="single"
              @click="handleUpdate"
              v-hasPermi="['student:item:edit']"
            >修改
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['student:item:remove']"
            >删除
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="el-icon-download"
              size="mini"
              @click="handleExport"
              v-hasPermi="['student:item:export']"
            >导出
            </el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="itemList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center"/>
          <!--      <el-table-column label="加分项ID" align="center" prop="plusGradeItemId" />-->
          <!--      <el-table-column label="荣誉数据ID" align="center" prop="plusGradeItemGloryId"/>-->
          <el-table-column label="用户名" align="center" prop="userName"/>
          <el-table-column label="用户昵称" align="center" prop="nickName"/>
          <el-table-column label="荣誉标签" align="center" prop="plusGradeItemGloryLabel" :show-overflow-tooltip="true"/>
          <el-table-column label="获得时间" align="center" prop="plusGradeItemTime" width="180">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.plusGradeItemTime, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="证明材料" align="center" prop="plusGradeItemUrl">
            <template slot-scope="scope">
          <span>
            <el-link @click="handleQueryImage(scope)" target="_blank">查看
              <i class="el-icon-view el-icon--right"/>
            </el-link>
          </span>
            </template>
          </el-table-column>
          <!--      <el-table-column label="用户ID" align="center" prop="userId" />-->
          <el-table-column label="分数" align="center" prop="gloryGrade"/>
          <el-table-column label="学院审核" align="center" prop="statusCollege" :formatter="statusCollegeFormat">
          </el-table-column>
          <el-table-column label="学生处审核" align="center" prop="statusOffice" :formatter="statusOfficeFormat">
            <!--            这里需要放置一个按钮来进行控制啦~-->
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.statusOffice"
                active-value="0"
                inactive-value="1"
                @change="handleStatusOfficeChange(scope.row)"
              ></el-switch>
            </template>

          </el-table-column>
          <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true"/>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-cpu"
                @click="handleCalculate(scope.row)"
                v-hasPermi="['student:item:calc']"
              >算分
              </el-button>

              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['student:item:edit']"
              >修改
              </el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['student:item:remove']"
              >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />


      </el-col>
    </el-row>

    <!-- 添加或修改加分项对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="auto">
        <el-form-item label="荣誉" prop="plusGradeItemGloryId">
          <el-cascader :options="options"
                       ref="myCascader"
                       v-model="form.plusGradeItemGloryId"
                       :leafOnly="true"
                       @change="cascaderChange"
                       :props="{ expandTrigger: 'hover' }"
                       :show-all-levels="false"

                       :key="isResouceShow">

          </el-cascader>

        </el-form-item>
        <el-form-item label="获得时间" prop="plusGradeItemTime">
          <el-date-picker clearable size="small"
                          v-model="form.plusGradeItemTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="选择加分项获得时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="证明材料" prop="plusGradeItemUrl">
          <fileUpload v-model="form.plusGradeItemUrl"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <!--        <el-button @click="cancel">取 消</el-button>-->
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {treeselect} from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import FileUpload from "@/components/FileUpload";
import {
  addItem,
  calculate,
  delItem,
  exportItem,
  getItem,
  getListAllTypeAndData,
  listItem,
  updateItem
} from "@/api/students/item";
import {changeCollegeStatus, changeOfficeStatus} from "@/api/teacher/approval";

export default {
  name: "Approval",
  components: {Treeselect, FileUpload},
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 加分项表格数据
      itemList: [],
      // 弹出层标题
      title: '',
      // 部门树选项
      deptOptions: undefined,
      // 部门名称
      deptName: undefined,
      // 是否显示弹出层
      open: false,
      // 学院状态字典
      statusCollegeOptions: [],
      // 学生处状态字典
      statusOfficeOptions: [],
      // 查询参数，搜索用到啦~
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        plusGradeItemGloryId: null,
        plusGradeItemTime: null,
        plusGradeItemUrl: null,
        userId: null,
        gloryGrade: null,
        statusCollege: null,
        statusOffice: null,
        deptId: null
      },
      // 表单参数
      form: {},
      defaultProps: {
        children: "children",
        label: "label"
      },
      //下拉框缓存荣誉数据
      options: [],
      //防止渲染报错
      isResouceShow: 0,
      // 表单校验
      rules: {
        plusGradeItemGloryId: [
          {required: true, message: "荣誉不能为空", trigger: "blur"}
        ],
        plusGradeItemUrl: [
          {required: true, message: "证明材料不能为空", trigger: "blur"}
        ],

      }
    }
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);
    }
  },
  created() {
    this.getList();
    this.getTreeselect();
    this.getDicts("sys_user_sex").then(response => {
      this.sexOptions = response.data;
    });
    this.getDicts('sys_normal_disable').then(response => {
      this.statusOfficeOptions = response.data
      this.statusCollegeOptions = response.data
    })
    this.getListAllTypeAndData();
  },
  methods: {
    // 学院状态字典翻译
    statusCollegeFormat(row, column) {
      return this.selectDictLabel(this.statusCollegeOptions, row.statusCollege)
    },
    // 学生处状态字典翻译
    statusOfficeFormat(row, column) {
      return this.selectDictLabel(this.statusOfficeOptions, row.statusOffice)
    },
    //获取荣誉数据
    getListAllTypeAndData() {
      getListAllTypeAndData().then(response => {
        ++this.isResouceShow;
        this.options = response;
      })
    },
    /** 查询荣誉项列表 */
    getList() {
      this.loading = true
      listItem(this.queryParams).then(response => {
        this.itemList = response.rows
        this.total = response.total
        this.loading = false
      })

    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      treeselect().then(response => {
        this.deptOptions = response.data;
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.deptId = data.id;
      this.getList();
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        plusGradeItemId: null,
        plusGradeItemGloryId: null,
        plusGradeItemTime: null,
        plusGradeItemUrl: null,
        userId: null,
        gloryGrade: null,
        statusCollege: '1',
        statusOffice: '1',
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
      ++this.isResouceShow;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
      ++this.isResouceShow;
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.plusGradeItemId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true;
      this.title = '添加加分项';
      ++this.isResouceShow;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset()
      ++this.isResouceShow;
      const plusGradeItemId = row.plusGradeItemId || this.ids
      getItem(plusGradeItemId).then(response => {
        this.form = response.data
        this.open = true
        this.title = '修改加分项'
        this.loading = false;
      })
    },

    /** 重置密码按钮操作 */
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.loading = true;
          if (this.form.plusGradeItemId != null) {
            updateItem(this.form).then(response => {
              this.msgSuccess('修改成功')
              this.open = false
              this.getList()
              this.loading = false;
            })
          } else {
            addItem(this.form).then(response => {
              this.msgSuccess('新增成功')
              this.open = false
              this.getList()
              this.loading = false;
            })
          }
        }
      })
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const plusGradeItemIds = row.plusGradeItemId || this.ids
      this.$confirm('是否确认删除加分项编号为"' + plusGradeItemIds + '"的数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function () {
        return delItem(plusGradeItemIds)
      }).then(() => {
        this.getList()
        this.msgSuccess('删除成功')
      })
    },

    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams
      this.$confirm('是否确认导出所有加分项数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function () {
        return exportItem(queryParams)
      }).then(response => {
        this.download(response.msg)
      })
    },
    /** 处理查询图片  */
    handleQueryImage(scope) {
      if (scope.row.plusGradeItemUrl == null || scope.row.plusGradeItemUrl == '') {
        this.msgError('无匹配数据')
      } else {
        const aLink = document.createElement('a')
        aLink.href = scope.row.plusGradeItemUrl
        aLink.target = '_blank'
        aLink.click()
      }
    },

    //这里是绑定弹出层的级联菜单
    cascaderChange() {
      //我们需要显示最后一个叶子的值就可
      let x = this.$refs.myCascader.getCheckedNodes(true);
      //成功获取value，更新吧
      this.form.plusGradeItemGloryId = x[0].value;
      ++this.isResouceShow;
    },
    cascaderChange2() {
      let x = this.$refs.myCascader2.getCheckedNodes(true);
      ++this.isResouceShow;
      this.queryParams.plusGradeItemGloryId = x[0].value;
    },
    // 学生处审核状态修改
    handleStatusOfficeChange(row) {
      let text = row.statusOffice === "0" ? "启用" : "停用";
      this.$confirm('确认要"' + text + '""' + row.userName + '"用户的材料吗?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return changeOfficeStatus(row.plusGradeItemId, row.statusOffice);
      }).then(() => {
        this.msgSuccess(text + "成功");
      }).catch(function () {
        row.statusOffice = row.statusOffice === "0" ? "1" : "0";
      });
    },
    /** 异步算分操作！---也可能写成 */
    handleCalculate(row) {
      this.$confirm('确定触发异步算分机制吗?【请注意，异步算分机制可能需要重新登录才能看到最新算分结果】', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function () {
        return calculate(row.userId);
      }).then(response => {
        //算分结束后，显示信息即可。
        this.msgSuccess(response.msg);
      }).catch(e => {
        this.msgError(response.msg);
        console.warn(e);
      })
    }
  }
};
</script>
